<?php

class nmMemberConvo {
	
	var $nmconvo_db_version = "1.0";
	
	/*
	**data vars
	*/
	
	static $started_by;
	static $started_with;
	static $subject;
	static $message;
	
	
	/*
	** pagination vars
	*/
	
	static $convo_row_count;
	static $convo_per_page = 5;
	static $total_pages;
	static $total_convos;
	
	
	/*
	** plugin short name
	*/
	static $short_name = 'nmconvo';
		
	
	/*
	** plugin table name
	*/
	static $tblName = 'nm_convo';
	
	
	
	function renderUserArea()
	{
		global $wpdb ;
		global $current_user;
		get_currentuserinfo();
		
		
		if ( is_user_logged_in() ) { 
			ob_start();
	         $file = dirname(__FILE__).'/_template_convo.php';
			include($file);
			$output_string = ob_get_contents();
			ob_end_clean();
			return $output_string;
		}
		else
		{
		
			/*wp_redirect( home_url() ); exit;*/
			echo '<script type="text/javascript">
			window.location = "'.wp_login_url( get_permalink() ).'"
			</script>';
		}
		
	}
	
	/*
	This function is making directory in follownig path
	wp-content/uploads/user_uploads
	*/
	
	function makeUploadDirectory()
	{
		nmMemberConvo::$pathUploads = ABSPATH . 'wp-content/uploads/user_uploads/';
		if(!is_dir(nmMemberConvo::$pathUploads))
		{
			if(mkdir(nmMemberConvo::$pathUploads, 0777))
				return true;
			else
				return false;
		}
		else
		{
			return true;
		}
	}
	
	
	/*
	** Installing database table for this plugin: nm_convo
	*/
	public function nmconvo_install() {
		global $wpdb;
		global $nmconvo_db_version;
	
		$table_name = $wpdb->prefix . nmMemberConvo::$tblName;
		  
		$sql = "CREATE TABLE `$table_name` (
				`convo_id` INT( 8 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
				`started_by` INT( 7 ) NOT NULL ,
				`started_with` INT( 7 ) NOT NULL ,
				`subject` VARCHAR( 150 ) NOT NULL,
				`convo_thread` MEDIUMTEXT NOT NULL ,
				`read_by` VARCHAR( 150 ) DEFAULT '0',
				`deleted_by` VARCHAR( 150 ) DEFAULT '0',
				`last_sent_by` INT( 7 ) NOT NULL ,
				`sent_on` DATETIME NOT NULL
				);";
	
	   require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
	   dbDelta($sql);
	 
	   add_option("nmconvo_db_version", $nmconvo_db_version);
	}
	
	
	/*
	** It is making title with suject and latest message excerpt
	*/
	public function convoTitle($subject, $thread)
	{
		$thread = json_decode($thread);
		
		//Getting last message array
		$lastChunk = end($thread);
		$lastMessage = stripslashes(nmMemberConvo::fixLengthWords($lastChunk -> message, 6));
		//print_r($lastMessage);
		
		$html = "<strong>$subject</strong>";
		$html .= "<span style=\"color:#999\"> - $lastMessage</span>";
		return $html;
	}
	
	
	/*
	** It is making Parties (buddies names)
	*/
	public function convoParties($thread, $started_with = null)
	{
		global $current_user;
		get_currentuserinfo();
		
		$thread = json_decode($thread);
		
		//Getting last message array
		$lastChunk = end($thread);
		$otherBuddy = $lastChunk -> username;
		
		//check it is first convo
		if($otherBuddy === $current_user -> user_login)
		{
			$user_info = get_userdata($started_with);
			$html = "<strong>".__('me', nmMemberConvo::$short_name)."</strong>, ".$user_info->user_login;
		}
		else
		{
			$html = __('me', nmMemberConvo::$short_name) . ", <strong>$otherBuddy</strong>";
		}
			
		return $html;
	}
	
	
	
	/*
	Listing user files in admin
	*/
	public function renderListings()
	{
		$file = dirname(__FILE__).'/listings.php';
		include($file);
	}
	

  
  public function set_up_admin_page () {
	
	add_menu_page(	'UserConvo', 
					'NM Convo', 
					'manage_options', 
					'nmconvo-settings', 
					array('nmMemberConvo', 'show_admin_options'),
					'');
	
	}
	
	
	public function show_admin_options()
	{
		$file = dirname(__FILE__).'/options.php';
		include($file);
	}
	
	
  	/*
	** sending convo to user, NEW convo
	*/
	public function sendConvo()
	{
		global $current_user;
		get_currentuserinfo();
		
		global $wpdb;
		
		
		$thread[] = array('username'=> $current_user -> user_login,
						'userid'	=> $current_user -> ID,
						'message'	=> nmMemberConvo::$message,
						'senton'	=> time(),
						);
		
		
		$dt = array('started_by'	=> $current_user -> ID,
					'started_with'	=> nmMemberConvo::$started_with,
					'subject'		=> nmMemberConvo::$subject,
					'convo_thread'	=> json_encode($thread),
					'last_sent_by'	=> $current_user -> ID,
					'sent_on'		=> current_time('mysql')
					);
					 
					 
		/*var_dump($dt);
		exit;*/
		
		$wpdb -> insert($wpdb->prefix . nmMemberConvo::$tblName,
						$dt		
						);
		
		if($wpdb->insert_id)
			return true;
		else
			return false;
						
		//$wpdb->print_error(); 
	}
	
	/*
	**replying convo
	*/
	
	function replyConvo($convoID)
	{
		global $wpdb;
		global $current_user;
		get_currentuserinfo();
		
		$thread = array();
		
		$convo = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix . nmMemberConvo::$tblName."
								WHERE convo_id = $convoID");
								
		//getting chunk
		$thread = json_decode($convo -> convo_thread, true);
								
		
		//updating chunk
		$thread[] = array('username'=> $current_user -> user_login,
						'userid'	=> $current_user -> ID,
						'message'	=> nmMemberConvo::$message,
						'senton'	=> time(),
						);
		/*echo "<pre>";
		print_r($thread);
		echo "</pre>";
		exit;*/
		
		$dt = array('convo_thread'	=> json_encode($thread),
					'last_sent_by'	=> $current_user -> ID,
					'read_by'		=> 0,
					'sent_on'		=> current_time('mysql')
					);
		
		
		$where = array('convo_id'	=> $convoID);
		
		$res = $wpdb -> update($wpdb->prefix . nmMemberConvo::$tblName,$dt, $where);
		
		
					
		return $res;
	}
	
	
	/*
	**deleting file
	*/
	public function deleteFile($fileid)
	{
		global $wpdb;
		$res = $wpdb->query(
						"
						DELETE FROM ".$wpdb->prefix . nmMemberConvo::$tblName."
						WHERE fileID = $fileid"
					);
		return $res;
	}
	
	
	/*
	** Get Current User Conversations
	*/
	
	function getUserConvos()
	{
		//echo "hello";
		global $wpdb;
		global $user_ID;
		
		$myrows = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix . nmMemberConvo::$tblName."
						  			   WHERE (started_by = $user_ID
									   OR started_with = $user_ID)
									   AND (deleted_by != $user_ID
									   AND deleted_by NOT LIKE '$user_ID,%'
									   AND deleted_by NOT LIKE '%,$user_ID')
									   ORDER BY sent_on DESC");
		
		/*$wpdb->show_errors();
		$wpdb->print_error(); */
		
		nmMemberConvo::$total_convos = nmMemberConvo::inboxCount(count($myrows));
		
		
	   	return $myrows;
	}
	
	/*
	** Get all conversations for admin view
	*/
	
	function getAllConvos()
	{
		//echo "hello";
		global $wpdb;
		global $user_ID;
		
		$myrows = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix . nmMemberConvo::$tblName."
						  			   ORDER BY sent_on DESC");
		
		/*$wpdb->show_errors();
		$wpdb->print_error(); */
		
		nmMemberConvo::$total_convos = nmMemberConvo::inboxCount(count($myrows));
		
		
	   	return $myrows;
	}
	
	
	/*
	** Deleting convo,
	*/
	
	function deleteConvo($cid)
	{
		//echo "hello";
		global $wpdb;
		global $user_ID;
		
		$del = $wpdb->get_col( "SELECT deleted_by FROM ".$wpdb->prefix . nmMemberConvo::$tblName."
						  		WHERE convo_id = $cid");
									   
		if($del[0] == 0)
		{
			$deleted_by = $user_ID;
		}
		else
		{
			///////// avoid mutiple cncatenation and concatinate userID
			$ids = explode(",",$del[0]);
			if(!in_array($user_ID,$ids)) $deleted_by = $del[0].','.$user_ID; else $deleted_by=$del[0];
		}
		
		// now updating for deleted_by
		
		$res = $wpdb->update($wpdb->prefix . nmMemberConvo::$tblName,
						array('deleted_by'	=> $deleted_by),
						array('convo_id' 	=> $cid)
					);
		
		
		/*$wpdb->show_errors();
		$wpdb->print_error(); */
		
	   return $res;
	}
	
	
	
	/*
	** Get Convo Detail
	*/
	
	function getConvoDetail($convoID)
	{
		//echo "hello";
		global $wpdb;
		
		$myrows = $wpdb->get_results( "SELECT * FROM ".$wpdb->prefix . nmMemberConvo::$tblName."
						  			   WHERE convo_id= $convoID
									   ORDER BY sent_on DESC");
	   return $myrows[0];
	}
	
	
	/*
	** Helper: getting fix lenght of string
	*/
	function fixLengthWords($pStr,$pLength)
	{
		$length = $pLength; // The number of words you want
	
		$text = strip_tags($pStr);
		/*echo $text;
		exit;*/
		$words = explode(' ', $text); // Creates an array of words	
		$words = array_slice($words, 0, $length);
		$str = implode(' ', $words);
		
		$str .= (count($words) < $pLength) ? '' : '...';
		
		return $str;
	}
	
	
	/*
	** inbox counter rendering
	*/
	
	function inboxCount($total)
	{
		if($total <= 0)
		{
			return '';
		}
		else
		{
			return "($total)";
		}
		
	}
	
	
	/*
	** getting unread messages
	*/
	
	function unreadConvo()
	{
		//getting new message counter
		global $wpdb;
		global $user_ID;
		
		$myrows = $wpdb->get_results( "SELECT COUNT(*) AS UNREAD FROM ".$wpdb->prefix . nmMemberConvo::$tblName."
						  			   WHERE (started_by = $user_ID
									   OR started_with = $user_ID)
									   AND last_sent_by != $user_ID
									   AND read_by = 0");
		
		/*$wpdb->show_errors();
		$wpdb->print_error(); 
		print_r($myrows);*/
		
		if($myrows[0] -> UNREAD > 0)
		{
			echo '<div class="nm-unread-alert">'.__('You have '.$myrows[0] -> UNREAD.' unread conversations', nmMemberConvo::$short_name).'</div>';
		}
	}
	
	/*
	** marking conversation as read
	*/
	function markAsRead($convo_id)
	{
		global $wpdb;
		global $user_ID;
		
		$dt = array('read_by'	=> $user_ID);
		
		
		$where = array('convo_id'	=> $convo_id);
		/*$where = "WHERE convo_id = $convo_id
					AND last_sent_by != $user_ID";*/
		
		$res = $wpdb -> update($wpdb->prefix . nmMemberConvo::$tblName,$dt, $where);
		
		$wpdb->show_errors();
		$wpdb->print_error();
	}
	
	
	/*
	** this is setting users array based on IDs so easily can get user info in_array index
	*/
	function setUsersByID($arrUsers)
	{
		$arr = array();
		foreach($arrUsers as $user)
		{
			$arr[$user -> ID] = $user;
		}
		
		/*echo "<pre>";
		print_r($arr);
		echo "</pre>";*/
		return $arr;
		
	}
	
	/*
	** User conversation list
	*/
	
	function listUserConvos()
	{
		$file = dirname(__FILE__).'/listings-all.php';
		include($file);	
	}
	
	/*
	** sending user an email with instructino/attachment
	*/
	
	function sendConfirmationEmail()
	{
		//date_default_timezone_set('America/Toronto');
		
		$php_mailer_path = dirname(__FILE__) . '/mailer/class.phpmailer.php';		
		
		require_once($php_mailer_path);
		
		$mail             = new PHPMailer(); // defaults to using php "mail()"

		$mail->IsSendmail(); // telling the class to use SendMail transport
		
		$body             = file_get_contents('contents.html');
		$body             = eregi_replace("[\]",'',$body);
		
		$mail->AddReplyTo("name@yourdomain.com","First Last");
		
		$mail->SetFrom('name@yourdomain.com', 'First Last');
		
		$mail->AddReplyTo("name@yourdomain.com","First Last");
		
		$address = "whoto@otherdomain.com";
		$mail->AddAddress($address, "John Doe");
		
		$mail->Subject    = "PHPMailer Test Subject via Sendmail, basic";
		
		$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
		
		$mail->MsgHTML($body);
		
		$mail->AddAttachment("images/phpmailer.gif");      // attachment
		$mail->AddAttachment("images/phpmailer_mini.gif"); // attachment
		
		if(!$mail->Send()) {
		  echo "Mailer Error: " . $mail->ErrorInfo;
		} else {
		  echo "Message sent!";
		}
		
	}
	
   
}